Popular Searches
Popular Course Categories
Popular Courses

if/else Rendering Patterns

if/else Rendering Patterns

React Events and Conditional Rendering

if/else Rendering Patterns in React JS

if/else Rendering Patterns are used in React JS to display different UI elements or components depending on whether a condition is true or false. React uses standard JavaScript conditional statements to decide what content should be rendered. These patterns are useful for login screens, dashboards, loading indicators, error messages, user roles, product availability, and form validation.

Course: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. What Is if/else Rendering in React?

if/else rendering means using JavaScript if and else statements to determine which JSX content a React component should return. If the condition is true, one output is selected; otherwise, another output is selected.

Example:

function App() {
  const isLoggedIn = true;
  if (isLoggedIn) {
    return <h2>Welcome Back!</h2>;
  } else {
    return <h2>Please Log In</h2>;
  }
}
export default App;

Output: Welcome Back!

Explanation: Since isLoggedIn is true, the component returns the Welcome Back heading. If the value changes to false, it returns the Please Log In heading instead.


2. Why Are if/else Rendering Patterns Important?

These patterns help developers create interfaces that respond to application data and user interactions.

  • Display different screens for logged-in and logged-out users.
  • Show loading messages while data is being fetched.
  • Display an error message when an operation fails.
  • Show success or failure messages after a form submission.
  • Display different dashboard sections based on a user role.
  • Show product availability or out-of-stock messages.
  • Display different content based on a user's subscription status.
  • Handle empty data and search results.

Real-World Examples

Situation Condition Rendered Content
Login system User is logged in User dashboard
Login system User is logged out Login form
Data fetching Data is loading Loading indicator
Form validation Input is invalid Error message
Shopping application Product is available Add to Cart button
Shopping application Product is unavailable Out of Stock message

3. Basic if Statement for Rendering

The if statement executes a block of JavaScript when a condition is true. In React, you can use it before the return statement to decide which JSX to render.

Syntax:

if (condition) {
  return JSX;
}
return defaultJSX;

Example:

function Greeting() {
  const isAdmin = true;
  if (isAdmin) {
    return <h2>Welcome Admin!</h2>;
  }
  return <h2>Welcome User!</h2>;
}
export default Greeting;

Explanation: When isAdmin is true, the component returns the admin greeting. If the condition is false, execution continues to the final return statement.

Important: JavaScript if statements are not written directly as statements inside JSX markup. Put the conditional logic in the component's JavaScript section or use an expression such as a ternary operator inside JSX.


4. if/else Statement for Two Different Outputs

The if/else statement allows you to choose between two outcomes. It is useful when both the true and false conditions need different content.

Syntax:

if (condition) {
  // Code or JSX for the true condition
} else {
  // Code or JSX for the false condition
}

Example:

function App() {
  const isLoggedIn = false;
  if (isLoggedIn) {
    return (
      <div>
        <h2>Dashboard</h2>
        <p>You are logged in.</p>
      </div>
    );
  } else {
    return (
      <div>
        <h2>Login Page</h2>
        <p>Please log in to continue.</p>
      </div>
    );
  }
}
export default App;

Output: Login Page with the message Please log in to continue.

Explanation: Since the value is false, React renders the JSX returned by the else block.


5. if/else Rendering Using a Variable

You can store JSX in a variable and then return it. This approach is useful when you want to keep the main JSX structure consistent while changing one part of the content.

Example:

function App() {
  const isLoggedIn = true;
  let content;
  if (isLoggedIn) {
    content = <h2>Welcome Back!</h2>;
  } else {
    content = <h2>Please Log In</h2>;
  }
  return (
    <div>
      <h1>User Portal</h1>
      {content}
    </div>
  );
}
export default App;

Explanation: The variable content stores the JSX selected by the condition. The main component then renders that variable inside the surrounding layout.

Advantages

  • Keeps the main JSX structure readable.
  • Works well when a component has multiple rendering branches.
  • Allows conditional content to be prepared before the final return.
  • Can reduce repeated markup when used carefully.

6. if/else if/else for Multiple Conditions

When there are more than two possible outcomes, use if, else if, and else. The conditions are checked in order, and the first matching branch is executed.

Example:

function App() {
  const marks = 78;
  let result;
  if (marks >= 90) {
    result = "Grade A";
  } else if (marks >= 75) {
    result = "Grade B";
  } else if (marks >= 50) {
    result = "Grade C";
  } else {
    result = "Fail";
  }
  return <h2>Result: {result}</h2>;
}
export default App;

Output: Result: Grade B

Explanation: The marks are 78. The first condition is false, while the second condition is true. Therefore, the component displays Grade B.

Important Points

  • Conditions are evaluated from top to bottom.
  • Only the first matching branch is executed.
  • The final else branch handles all remaining cases.
  • Arrange conditions carefully to avoid unreachable branches.

7. Returning Different Components with if/else

React components can return different child components depending on a condition. This is useful when different application states require separate interfaces.

Example:

function AdminDashboard() {
  return <h2>Admin Dashboard</h2>;
}
function UserDashboard() {
  return <h2>User Dashboard</h2>;
}
function App() {
  const isAdmin = true;
  if (isAdmin) {
    return <AdminDashboard />;
  } else {
    return <UserDashboard />;
  }
}
export default App;

Explanation: When isAdmin is true, React renders the AdminDashboard component. Otherwise, it renders UserDashboard.

Security note: Conditional rendering can hide or show interface elements, but it does not provide real access control. Permissions must also be enforced by the backend.


8. Using if/else with Props

Props allow a parent component to pass information to a child component. The child can use those values to decide what to display.

Example:

function UserStatus({ isOnline }) {
  if (isOnline) {
    return <p>User is Online</p>;
  } else {
    return <p>User is Offline</p>;
  }
}
function App() {
  return (
    <div>
      <UserStatus isOnline={true} />
      <UserStatus isOnline={false} />
    </div>
  );
}
export default App;

Explanation: The first component receives true and renders Online. The second receives false and renders Offline.


9. Using if/else with State

The useState Hook allows a component to store information that can change. When state changes, React renders the component again and evaluates its conditional logic using the updated value.

Example: Login and Logout

import { useState } from "react";
function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  if (isLoggedIn) {
    return (
      <div>
        <h2>Welcome to Your Dashboard</h2>
        <button onClick={() => setIsLoggedIn(false)}>
          Logout
        </button>
      </div>
    );
  }
  return (
    <div>
      <h2>Please Log In</h2>
      <button onClick={() => setIsLoggedIn(true)}>
        Login
      </button>
    </div>
  );
}
export default App;

Explanation: The initial state is false, so the login interface appears. Clicking Login updates the state to true and displays the dashboard. Clicking Logout sets the state back to false.


10. Early Return Pattern

An early return is a rendering pattern in which a component returns immediately when a particular condition is met. It is useful for handling special cases such as loading, errors, missing data, or unauthorized views.

Example:

function Profile({ user, isLoading, hasError }) {
  if (isLoading) {
    return <p>Loading profile...</p>;
  }
  if (hasError) {
    return <p>Unable to load profile.</p>;
  }
  if (!user) {
    return <p>User not found.</p>;
  }
  return (
    <div>
      <h2>{user.name}</h2>
      <p>{user.email}</p>
    </div>
  );
}
export default Profile;

Explanation: The component checks loading, error, and missing-user conditions in order. If none applies, it renders the profile information.

Benefits of Early Returns

  • Handle exceptional states before the main UI.
  • Reduce deeply nested conditional blocks.
  • Improve code readability.
  • Make loading, error, and empty states easier to identify.

11. Rendering Nothing with if/else and null

Sometimes a component should not display any content when a condition is met. React allows a component to return null to render nothing.

Example:

function Notification({ show }) {
  if (!show) {
    return null;
  } else {
    return <p>You have a new notification!</p>;
  }
}
export default Notification;

Explanation: When show is false, the component returns null. When it is true, the notification paragraph is displayed.


12. if/else Rendering for Loading and Error States

Data-driven applications often need to display different UI states while information is loading or when an error occurs.

Example:

function DataView({ isLoading, error, data }) {
  if (isLoading) {
    return <p>Loading data...</p>;
  } else if (error) {
    return <p>Error: {error}</p>;
  } else if (!data || data.length === 0) {
    return <p>No data available.</p>;
  } else {
    return (
      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    );
  }
}
export default DataView;

Explanation: The component first checks whether data is loading. If not, it checks for an error, then for empty data. When data is available, it renders a list.


13. if/else Rendering for Form Validation

Conditional rendering can display different messages depending on whether a form input meets the required conditions.

Example:

import { useState } from "react";
function App() {
  const [email, setEmail] = useState("");
  const [submitted, setSubmitted] = useState(false);
  const isEmailEmpty = email.trim() === "";
  function handleSubmit(event) {
    event.preventDefault();
    setSubmitted(true);
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">Email:</label>
      <input
        id="email"
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
      />
      {submitted && (
        isEmailEmpty
          ? <p>Email is required.</p>
          : <p>Email field is not empty.</p>
      )}
      <button type="submit">Submit</button>
    </form>
  );
}
export default App;

Explanation: When the form is submitted, React checks whether the email field is empty. It displays the corresponding message. In a real application, you should also validate the email format and other business rules before accepting the form.


14. if/else Rendering for Product Availability

E-commerce applications can use conditional rendering to show different actions based on product availability.

Example:

function Product({ name, inStock }) {
  if (inStock) {
    return (
      <div>
        <h2>{name}</h2>
        <p>Available now</p>
        <button>Add to Cart</button>
      </div>
    );
  } else {
    return (
      <div>
        <h2>{name}</h2>
        <p>Out of Stock</p>
        <button disabled>Unavailable</button>
      </div>
    );
  }
}
export default Product;

Explanation: If inStock is true, the product's Add to Cart button is displayed. Otherwise, the component displays an Out of Stock message and a disabled button.


15. if/else Rendering Compared with the Ternary Operator

Both if/else statements and ternary expressions can select between different UI outputs. The main difference is where and how they are used.

Feature if/else Statement Ternary Operator
Syntax if (condition) { ... } else { ... } condition ? A : B
Location JavaScript statements in the component body JavaScript expression, including inside JSX
Readability Often clearer for complex logic Often concise for simple conditions
Multiple conditions Supports if/else if/else chains Can be nested, but deep nesting can be difficult to read
Use case Early returns, loading states, different layouts Simple two-way choices in JSX

if/else Example:

let message;
if (isLoggedIn) {
  message = "Welcome";
} else {
  message = "Please log in";
}
return <p>{message}</p>;

Ternary Example:

return (
  <p>{isLoggedIn ? "Welcome" : "Please log in"}</p>
);

16. Common Mistakes in if/else Rendering

Mistake 1: Writing an if Statement Directly Inside JSX

// Incorrect
return (
  <div>
    if (isLoggedIn) {
      <p>Welcome</p>
    }
  </div>
);

Correction: Put the if statement in JavaScript before the return statement or use a conditional expression inside JSX.

if (isLoggedIn) {
  return <p>Welcome</p>;
}
return <p>Please log in</p>;

Mistake 2: Forgetting a Return Statement

If you use a block-bodied arrow function or a normal function, remember to return the intended JSX. Without a return statement, the function may produce undefined instead of the expected content.

Mistake 3: Incorrect Condition Order

In an if/else if chain, a broad condition placed first may prevent later branches from running. Put more specific conditions before broader ones when necessary.

Mistake 4: Using Assignment Instead of Comparison

// Correct comparison
if (role === "admin") {
  return <h2>Admin Dashboard</h2>;
}

Use comparison operators such as === to check values rather than accidentally assigning a value in the condition.

Mistake 5: Deeply Nested Conditional Logic

Too many nested if/else blocks can make components hard to maintain. Consider using early returns, helper functions, variables, or separate components.


17. Best Practices for if/else Rendering

  • Use clear condition names, such as isLoggedIn, isLoading, and hasError.
  • Use early returns for loading, error, and missing-data states.
  • Use if/else when the two branches require different layouts or complex logic.
  • Use a ternary operator for simple inline choices.
  • Keep the conditions easy to understand and test.
  • Avoid unnecessary nested if/else blocks.
  • Ensure each branch returns the correct JSX or a deliberate null.
  • Use unique keys when rendering arrays of elements.
  • Test the true and false outcomes of each condition.
  • Do not rely on hidden UI alone to protect private data or restricted actions.

18. Practical Project: Student Result Dashboard

Objective: Create a dashboard that displays a student's result based on marks. The component should show an Excellent, Passed, or Failed message depending on the student's score.

Complete Code:

function StudentResult({ name, marks }) {
  let result;
  if (marks >= 85) {
    result = "Excellent";
  } else if (marks >= 40) {
    result = "Passed";
  } else {
    result = "Failed";
  }
  return (
    <div>
      <h2>Student Result</h2>
      <p>Name: {name}</p>
      <p>Marks: {marks}</p>
      {result === "Excellent" ? (
        <h3>Excellent Performance!</h3>
      ) : result === "Passed" ? (
        <h3>Congratulations, You Passed!</h3>
      ) : (
        <h3>You Need More Practice.</h3>
      )}
    </div>
  );
}
function App() {
  return (
    <div>
      <StudentResult name="Amit" marks={92} />
      <StudentResult name="Priya" marks={65} />
      <StudentResult name="Rahul" marks={28} />
    </div>
  );
}
export default App;

Project Explanation

  1. The StudentResult component receives a student's name and marks through props.
  2. The if/else if/else statements determine the result category.
  3. The conditional expression displays a suitable message for each result.
  4. The parent component renders three students with different marks.
  5. Each student displays a result based on their own score.

19. Interview Questions and Answers

Q1. What is if/else rendering in React?

Answer: It is the use of JavaScript if/else statements to select which JSX a component should return.

Q2. Can we use if/else directly inside JSX?

Answer: No. JavaScript if/else statements are statements, not expressions. Use them in the component's JavaScript logic or use an expression such as a ternary operator inside JSX.

Q3. What is an early return?

Answer: An early return exits a component function when a condition is met, often to handle loading, error, or missing-data states.

Q4. What is the difference between if and if/else?

Answer: An if statement handles a condition when it is true. An if/else statement provides an alternative branch when the condition is false.

Q5. When should we use else if?

Answer: Use else if when several mutually exclusive conditions determine which output should be selected.

Q6. Can if/else return different React components?

Answer: Yes. A component can return different child components depending on the condition.

Q7. Can props control if/else rendering?

Answer: Yes. Props can provide the values that a component checks to select its output.

Q8. Can state control if/else rendering?

Answer: Yes. When state changes, React renders the component again and evaluates the conditions using the updated state.

Q9. What does returning null do?

Answer: It tells React to render no visible content for that component.

Q10. How can you improve complex conditional rendering?

Answer: Use early returns, descriptive variables, helper functions, or smaller components to make the logic easier to read.


20. Practice Exercises

  1. Create a component that displays Welcome when a user is logged in and Login Required otherwise.
  2. Use if/else to display Pass or Fail based on a student's marks.
  3. Create an admin and user dashboard using different components.
  4. Display Loading, Error, Empty, or Success content based on props.
  5. Create a product component that displays Add to Cart or Out of Stock.
  6. Build a login/logout interface using useState.
  7. Create a student result dashboard using if/else if/else.
  8. Refactor a deeply nested conditional component using early returns.

21. Quick Revision Checklist

  • Understand how if/else rendering works in React.
  • Know how to use if, if/else, and if/else if/else.
  • Understand how to store JSX in a variable.
  • Know how to return different components conditionally.
  • Understand early returns and returning null.
  • Know how props and state control rendering.
  • Understand the difference between if/else and the ternary operator.
  • Avoid writing if statements directly inside JSX.
  • Keep conditions readable and test each branch.

22. Useful Learning Resources


Conclusion

if/else Rendering Patterns are essential for controlling which UI elements and components appear in a React application. They allow developers to handle login status, loading states, errors, form validation, user roles, and other conditions. By using if/else statements, multiple-condition branches, early returns, and JSX variables appropriately, developers can create clear, reusable, and maintainable React components.

To continue learning, explore the JustAcademy React JS Training Course and register for a course demo.

whatsapp